﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.WarehouseManagement;
using ThridGroup.ERP.WarehouseManagement;

namespace ThridGroup.ERP.Web.Controllers.WarehouseManagement
{
    /// <summary>
    /// 外协入库控制器
    /// </summary>
    [Route("OutsourcingWarehousing")]
    public class OutsourcingWarehousingController : Controller
    {
        /// <summary>
        /// 外协入库服务
        /// </summary>
        private readonly IOutsourcingWarehousingServices _outsourcingWarehousingServices;

        /// <summary>
        /// 构造函数
        /// </summary>
        public OutsourcingWarehousingController(IOutsourcingWarehousingServices outsourcingWarehousingServices)
        {
            _outsourcingWarehousingServices = outsourcingWarehousingServices;
        }

        /// <summary>
        /// 外协入库视图
        /// </summary>
        [HttpGet("OutsourcingWarehousingView")]
        public IActionResult OutsourcingWarehousingView()
        {
            return View();
        }

        /// <summary>
        /// 分页查询外协入库列表
        /// </summary>
        /// <param name="inOrderCode">入库单编号（模糊）</param>
        /// <param name="outsourcedOrders">外协工单（模糊）</param>
        /// <param name="vendor">供应商（模糊）</param>
        /// <param name="inOrderDate">入库日期（等值）</param>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <returns>外协入库列表及总数</returns>
        [HttpGet("GetList")]
        public async Task<IActionResult> GetList(string inOrderCode = null, string outsourcedOrders = null, string vendor = null, DateTime? inOrderDate = null, int page = 1, int limit = 10)
        {
            var query = new QueryOutsourcingWarehousingDto
            {
                InOrderCode = inOrderCode,
                OutsourcedOrders = outsourcedOrders,
                Vendor = vendor,
                InOrderDate = inOrderDate,
                Page = page,
                Limit = limit
            };
            try
            {
                var (data, total) = await _outsourcingWarehousingServices.GetListAsync(query);
                return Json(new { code = 0, msg = "获取成功", count = total, data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取失败：" + ex.Message, count = 0, data = new List<OutsourcingWarehousingListDto>() });
            }
        }

        /// <summary>
        /// 新增外协入库
        /// </summary>
        [HttpPost("Add")]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> Add(CreateOutsourcingWarehousingDto dto)
        {
            if (dto == null)
                return Json(new { code = 1, msg = "参数不能为空" });
            try
            {
                var result = await _outsourcingWarehousingServices.AddOutsourcingWarehousingAsync(dto);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "添加成功" : "添加失败" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }
        /// <summary>
        /// 生成退货单编号
        /// </summary>
        [HttpGet("GetInOrderCode")]
        public async Task<JsonResult> GetInOrderCode()
        {
            try
            {
                // 生成格式：GD + 年月日 + 4位随机数
                var today = DateTime.Now;
                string inOrderCode = "GD" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, inOrderCode = inOrderCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成生产工单编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除外协入库
        /// </summary>
        [HttpPost("BatchDelete")]
        public async Task<JsonResult> BatchDelete(List<int> ids)
        {
            if (ids == null || ids.Count == 0)
                return Json(new { code = 1, msg = "请选择要删除的记录" });
            await _outsourcingWarehousingServices.BatchDeleteAsync(ids);
            return Json(new { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 修改单据状态（如将草稿设为已完成）
        /// </summary>
        [HttpPost("UpdateState")]
        public async Task<JsonResult> UpdateState(int id, int state)
        {
            var result = await _outsourcingWarehousingServices.UpdateStateAsync(id, state);
            return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "修改成功" : "修改失败" });
        }

        /// <summary>
        /// 根据ID获取外协入库详情（反填）
        /// </summary>
        [HttpGet("GetById")]
        public async Task<JsonResult> GetById(int id)
        {
            var dto = await _outsourcingWarehousingServices.GetByIdAsync(id);
            if (dto == null)
                return Json(new { code = 1, msg = "未找到数据" });
            return Json(new { code = 0, data = dto });
        }

        /// <summary>
        /// 修改外协入库
        /// </summary>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> Update(int id, CreateOutsourcingWarehousingDto dto)
        {
            if (dto == null)
                return Json(new { code = 1, msg = "参数不能为空" });
            try
            {
                var result = await _outsourcingWarehousingServices.UpdateAsync(id, dto);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "修改成功" : "修改失败" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除单个外协入库
        /// </summary>
        [HttpPost("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> Delete(int id)
        {
            var result = await _outsourcingWarehousingServices.DeleteAsync(id);
            return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "删除成功" : "删除失败" });
        }
    }
}
